<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-loading="dialogInfo.btLoading"
    :bt-list="dialogInfo.btList"
  >
    <div class="dialog-table">
      <page-filter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-button>
          <div class="dialog-table-header">
            <div class="header-left">
              <div class="lable">产品名称：{{ info.commonName }}</div>
              <div class="lable">
                消耗单价：{{ $fn.TripartiteMethod(info.consumePrice) }}
              </div>
            </div>
            <div class="header-right">
              <div class="scan-groups">
                <el-input
                  v-model="filterInfo.sacnCode"
                  :clearable="true"
                  ref="scan"
                  placeholder="请扫码二维码/个体码"
                  @keyup.enter.native="scan"
                  @input="(e) => (filterInfo.sacnCode = validSe(e))"
                >
                </el-input>
              </div>
            </div>
          </div>
          <div>
            <el-button style="margin-right: 10px" @click="changeNumberAll(true)"
              >一键填充数量</el-button
            >
            <el-button @click="changeNumberAll(false)">一键清空</el-button>
          </div>
        </template>
      </page-filter>
    </div>
    <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
      <dialog-table
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        ref="depotTable"
        v-model:data="tableInfo.data"
        :api="api"
        :check-box="false"
        :pager="false"
        :tabIndex="true"
        :listen-height="false"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-qty="scope">
          <el-input-number
            style="width: 100px"
            v-model="scope.row.qty"
            controls-position="right"
            :precision="0"
            v-enterNumber
            :disabled="scope.row.stockQty - (scope.row.frozenQty || 0) === 0"
            :max="scope.row.stockQty - (scope.row.frozenQty || 0)"
            :min="0"
          ></el-input-number>
        </template>
      </dialog-table>
    </el-form>
  </page-dialog>
</template>

<script setup name="IndividualDetails">
import PageDialog from '@/components/PageDialog/index'
import PageFilter from '@/components/PageFilter/index'
import { withTableReceivingOrderAddDetailAll } from '@/api/stock'
import DialogTable from '@/components/DialogTable/index'
import _ from 'lodash'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps({
  api: {
    type: Function,
    default: withTableReceivingOrderAddDetailAll,
  },
  showDialog: {
    type: Boolean,
  },
  query: {
    type: Object,
    default: function () {
      return {}
    },
  },
  info: {
    type: Object,
    default: function () {
      return {}
    },
  },
})
// 过滤相关配置
const filterInfo = reactive({
  query: {
    ...props.query,
  },
  sacnCode: '',
  list: [{ type: 'slot', value: 'button' }],
})
// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],
  selections: [],
  fieldList: [
    { label: '个体码', value: 'uniqueCode' },
    { label: '原厂码', value: 'factorySubCode' },
    { label: '生产批号', value: 'batchNumber' },
    { label: '生产日期', value: 'productionDate' },
    { label: '失效日期', value: 'validityDate' },
    { label: '病人名称', value: 'patientName' },
    { label: '住院号', value: 'patientNo' },
    { label: '消耗时间', value: 'consumeTime' },
    {
      label: '消耗数量',
      value: 'consumeQty',
      type: 'column',
      formatter: proxy.$fn.qtyFormatter,
    },
    {
      label: '收货数量',
      value: 'qty',
      type: 'slot',
    },
  ],
})
// 弹窗相关
const dialogInfo = reactive({
  title: '选择个体',
  btLoading: false,
  btList: [
    { label: '关闭', event: hanhandleClosedleSave, show: true },
    { label: '保存', event: handleSave, show: true },
  ],
})
const scanInput = ref('')
const selectRow = ref('')
const isReturnShow = ref(true)

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emit('update:showDialog', newValue) // 更新父组件shows
  },
})

watch(
  () => tableInfo.data,
  (val) => {
    if (
      val &&
      isReturnShow.value &&
      props.info.details &&
      props.info.details.length
    ) {
      isReturnShow.vlaue = false
      tableInfo.data.forEach((row) => {
        row['qty'] = 0
        props.info.details.forEach((item) => {
          // let flag = (item.code && row.code === item.code) || (item.unityCode && row.unityCode === item.unityCode) || (item.factorySubCode && row.factorySubCode === item.factorySubCode)
          let flag = row.withTableRecordId === item.withTableRecordId
          if (flag) {
            row['qty'] = item.qty
          }
        })
      })
    }
  },
  {
    deep: true,
  }
)

// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
function scan() {
  const code = filterInfo.sacnCode
  if (!code) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '请扫码二维码/个体码',
    })
    return
  }
  if (tableInfo.data.length) {
    let index = _.findIndex(tableInfo.data, function (i) {
      return (
        i.code === code || i.uniqueCode === code || i.factorySubCode === code
      )
    })

    if (index > -1) {
      let item = tableInfo.data[index]
      if (item.qty && item.qty + 1 <= item.consumeQty) {
        tableInfo.data[index] = { ...item, qty: item.qty + 1 }
      } else if (!item.qty) {
        item['qty'] = 1
      } else if (item.qty && item.qty + 1 > item.consumeQty) {
        proxy.$message({
          message: '该产品收货数量超出消耗数量！',
          type: 'warning',
          duration: 3500,
          showClose: true,
        })
      }
    } else {
      proxy.$message({
        message: '该个体详情中未查询到相关产品',
        type: 'warning',
        duration: 3500,
        showClose: true,
      })
    }
    filterInfo.sacnCode = ''
    proxy.$refs.scan.focus()
  }
}
function sumArr(arr) {
  let sum = 0
  arr.map((i) => {
    sum += Number(i.qty)
  })
  return sum
}
function sumPrice(arr) {
  let sum = 0
  arr.map((i) => {
    sum += Number(i.qty) * i.price
  })
  return sum
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emit('reset')
}
function handleSave() {
  let arr = tableInfo.data.filter((item) => item.qty > item.consumeQty)
  if (arr.length) {
    proxy.$message({
      message: '该产品收货数量超出消耗数量！',
      type: 'warning',
      duration: 3500,
      showClose: true,
    })
    return
  }
  let list = tableInfo.data.filter((item) => item.qty > 0)
  if (!list.length) {
    proxy.$message({
      duration: 3500,
      type: 'warning',
      showClose: true,
      message: '收货数量不能全为空或0',
    })
    return
  }
  const qtyTotal = sumArr(list)
  const sumPrice = sumPrice(list)
  const param = {
    ...props.info,
    qty: qtyTotal,
    // sumPrice: sumPrice,
    details: [...tableInfo.data],
  }
  emit('callback', param)
  hanhandleClosedleSave()
}
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function changeNumberAll(isAll) {
  if (isAll) {
    tableInfo.data.forEach((row) => {
      row.qty = row.consumeQty || 0
    })
  } else {
    tableInfo.data.forEach((row) => {
      row.qty = 0
    })
  }
}
</script>

<style scoped lang="scss">
:deep(.filter-item) {
  width: 100%;
}
.text-style {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
</style>
